package me.zhenqu.redis.utils;

import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: yibing.tan
 * Date: 11-11-14
 * Time: 下午4:21
 * To change this template use File | Settings | File Templates.
 */
public class ObjectCoder<T> extends CacheCoder<T> {
    private Class<T> clazz;

    public ObjectCoder(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public byte[] encode(T o) {
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        try{
            ObjectOutputStream oStream = new ObjectOutputStream( bStream );
            oStream.writeObject ( o );
            return bStream.toByteArray();
        }catch (IOException e){
            return null;
        }
    }

    @Override
    public T decode(byte[] val, int offset, int size) {
        try{
            ByteArrayInputStream in = new ByteArrayInputStream(val);
            ObjectInputStream is = new ObjectInputStream(in);
            try {
                return (T)is.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
